'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { IconPencil, IconTrash, IconLoader2 } from '@tabler/icons-react';

interface DietRecord {
  id: string;
  foodName: string;
  amount: number;
  unit: string;
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
  mealTime: Date;
  notes?: string | null;
}

interface Props {
  records: DietRecord[];
  onRecordDeleted?: () => void;
}

export default function DietRecordList({ records, onRecordDeleted }: Props) {
  const router = useRouter();
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这条记录吗？')) {
      return;
    }

    setDeletingId(id);
    try {
      const res = await fetch(`/api/diet/record/${id}`, {
        method: 'DELETE',
        credentials: 'include',
      });

      if (!res.ok) {
        throw new Error('删除失败');
      }

      onRecordDeleted?.();
    } catch (error) {
      console.error('删除记录失败:', error);
      alert('删除失败，请稍后重试');
    } finally {
      setDeletingId(null);
    }
  };

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleString('zh-CN', {
      month: 'numeric',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
    });
  };

  return (
    <div className="space-y-4">
      {records.map(record => (
        <div
          key={record.id}
          className="bg-white p-4 rounded-lg shadow-sm border border-gray-100"
        >
          <div className="flex justify-between items-start">
            <div>
              <h3 className="text-lg font-medium">{record.foodName}</h3>
              <p className="text-gray-500 text-sm">
                {formatDate(record.mealTime)}
              </p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => router.push(`/diet-record/edit/${record.id}`)}
                className="p-1.5 hover:bg-gray-100 rounded-full transition-colors"
                title="编辑"
              >
                <IconPencil className="w-4 h-4 text-gray-600" />
              </button>
              <button
                onClick={() => handleDelete(record.id)}
                disabled={deletingId === record.id}
                className="p-1.5 hover:bg-gray-100 rounded-full transition-colors"
                title="删除"
              >
                {deletingId === record.id ? (
                  <IconLoader2 className="w-4 h-4 text-gray-600 animate-spin" />
                ) : (
                  <IconTrash className="w-4 h-4 text-gray-600" />
                )}
              </button>
            </div>
          </div>

          <div className="mt-2 grid grid-cols-4 gap-4 text-sm">
            <div>
              <p className="text-gray-500">数量</p>
              <p>{record.amount} {record.unit}</p>
            </div>
            <div>
              <p className="text-gray-500">热量</p>
              <p>{record.calories} kcal</p>
            </div>
            <div>
              <p className="text-gray-500">蛋白质</p>
              <p>{record.protein}g</p>
            </div>
            <div>
              <p className="text-gray-500">碳水</p>
              <p>{record.carbs}g</p>
            </div>
          </div>

          {record.notes && (
            <p className="mt-2 text-sm text-gray-600">{record.notes}</p>
          )}
        </div>
      ))}
    </div>
  );
} 